<?php
/**
 * IG_Editor_CkEditor
 *
 * @author maomao.thx@gmail.com
 * @copyright Copyright (c) 2009 Green Shore (http://www.iwgame.com)
 * @version $Id: CkEditor.php 586 2011-05-31 10:07:18Z mmxie $
 */
class IG_Editor_CkEditor
{
    public $basePath = '/scripts/ckeditor/';
    public $skin = 'v2';
    public $language = 'zh-cn';
    public $width;
    public $height;
    public $config = array();
    public $initialized = false;
    public $textareaAttributes = array("rows" => 18 , "cols" => 60);
    public $timestamp = "B1GG4Z6";
    private $events = array();
    private $globalEvents = array();

    /**
     *
     * @param string $basePath
     */
    public function __construct($basePath = null)
    {
        if ($basePath != null)
        {
            $this->basePath = $basePath;
        }
    }
    /**
     *
     * @param $name
     * @param $value
     * @param $config
     * @param $events
     */
    public function build($name, $value = "")
    {
        $textarea = new Zend_Form_Element_Textarea($name, $this->textareaAttributes);
        $textarea->setValue(htmlspecialchars_decode($value));
        //$textarea->setValue($value);
        $out = $textarea->render();

        return $out;
    }

    public function script($name, $config = array(), $events = array())
    {
        if (!array_key_exists('skin', $config)) {
            $config['skin'] = $this->skin;
        }
        $_config = $this->configSettings($config, $events);
        if (! empty($_config))
            $script = "CKEDITOR.replace('" . $name . "', " . $this->jsEncode($_config) . ");";
        else
            $script = "CKEDITOR.replace('" . $name . "');";

        $js = sprintf('%s(document).ready(function() { %s });',
                ZendX_JQuery_View_Helper_JQuery::getJQueryHandler(),
                $script
        );
        return $js;
    }

    /**
     * see ckeditor help
     *
     * @param array $config
     * @param array $events
     * @return array
     */
    private function configSettings($config = array(), $events = array())
    {
        $_config = $this->config;
        $_events = $this->events;
        if (is_array($config) && ! empty($config))
        {
            $_config = array_merge($_config, $config);
        }
        if (is_array($events) && ! empty($events))
        {
            foreach ($events as $eventName => $code)
            {
                if (! isset($_events[$eventName]))
                {
                    $_events[$eventName] = array();
                }
                if (! in_array($code, $_events[$eventName]))
                {
                    $_events[$eventName][] = $code;
                }
            }
        }
        if (! empty($_events))
        {
            foreach ($_events as $eventName => $handlers)
            {
                if (empty($handlers))
                {
                    continue;
                }
                else if (count($handlers) == 1)
                {
                    $_config['on'][$eventName] = '@@' . $handlers[0];
                }
                else
                {
                    $_config['on'][$eventName] = '@@function (ev){';
                    foreach ($handlers as $handler => $code)
                    {
                        $_config['on'][$eventName] .= '(' . $code . ')(ev);';
                    }
                    $_config['on'][$eventName] .= '}';
                }
            }
        }
        return $_config;
    }

    /**
     * see ckeditor help, encode config array to js string
     *
     * @param array $val
     * @return string
     */
    private function jsEncode($val)
    {
        if (is_null($val))
        {
            return 'null';
        }
        if ($val === false)
        {
            return 'false';
        }
        if ($val === true)
        {
            return 'true';
        }
        if (is_scalar($val))
        {
            if (is_float($val))
            {
                // Always use "." for floats.
                $val = str_replace(",", ".", strval($val));
            }
            // Use @@ to not use quotes when outputting string value
            if (strpos($val, '@@') === 0)
            {
                return substr($val, 2);
            }
            else
            {
                static $jsonReplaces = array(array("\\" , "/" , "\n" , "\t" , "\r" , "\b" , "\f" , '"') , array('\\\\' , '\\/' , '\\n' , '\\t' , '\\r' , '\\b' , '\\f' , '\"'));
                $val = str_replace($jsonReplaces[0], $jsonReplaces[1], $val);
                if (strtoupper(substr($val, 0, 9)) == 'CKEDITOR.')
                {
                    return $val;
                }
                return '"' . $val . '"';
            }
        }
        $isList = true;
        for ($i = 0, reset($val); $i < count($val); $i ++, next($val))
        {
            if (key($val) !== $i)
            {
                $isList = false;
                break;
            }
        }
        $result = array();
        if ($isList)
        {
            foreach ($val as $v)
                $result[] = $this->jsEncode($v);
            return '[ ' . join(', ', $result) . ' ]';
        }
        else
        {
            foreach ($val as $k => $v)
                $result[] = $this->jsEncode($k) . ': ' . $this->jsEncode($v);
            return '{ ' . join(', ', $result) . ' }';
        }
    }
}